package ext.generic.part;

import com.ptc.core.components.forms.*;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.netmarkets.util.misc.NmContext;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import java.util.*;

import org.apache.log4j.Logger;

import wt.fc.WTReference;
import wt.fc.collections.WTCollection;

import wt.log4j.LogR;

import wt.part.WTPart;
import wt.part.WTProductInstance2;

import wt.session.SessionHelper;

import wt.util.*;

import wt.workflow.work.*;

import wt.part.*;

import wt.fc.*;

import wt.vc.VersionControlHelper;
import wt.vc.Iterated;

/**
 *该类主要处理用户的“收集相关随签对象”的请求
 */
public class CollectReviewObjectsFormProcessor extends DefaultObjectFormProcessor
{
    private static final String RESOURCE = "com.ptc.netmarkets.util.utilResource";
    private static final Logger log;
    protected String redirectURL;
    private static boolean VERBOSE = false;
    private static String CLASSNAME = CollectReviewObjectsFormProcessor.class.getName();

    static
    {
        try
        {
            log = LogR.getLogger(ext.generic.part.CollectReviewObjectsFormProcessor.class.getName());
            VERBOSE = (WTProperties.getLocalProperties()).getProperty("ext.generic.part.verbose", false);
        }
        catch (Exception exception)
        {
            throw new ExceptionInInitializerError(exception);
        }
    }

    public CollectReviewObjectsFormProcessor()
    {
        redirectURL = null;
    }

    /**
     *收集随签对象方法入口
     */
    public FormResult doOperation(NmCommandBean nmcommandbean, List list) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doOperation()");
//        Vector reviewObjs = new Vector();
        List reviewObjs = new ArrayList();
        java.util.Locale locale = SessionHelper.getLocale();
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
        if (nmcommandbean.getSelected().size() == 0)
        {
            FeedbackMessage feedbackmessage =
                new FeedbackMessage(FeedbackType.FAILURE, locale, new WTMessage("com.ptc.netmarkets.util.utilResource", "NO_OBJECT_SELECTED", null), null, new LocalizableMessage[]
                    { new WTMessage("com.ptc.netmarkets.util.utilResource", "NO_OBJECT_SELECTED", null) });
            formresult.addFeedbackMessage(feedbackmessage);
            formresult.setStatus(FormProcessingStatus.FAILURE);
            formresult.setNextAction(FormResultAction.REFRESH_CURRENT_PAGE);
            return formresult;
        }
        wt.fc.Persistable persistable = nmcommandbean.getPrimaryOid().getWtRef().getObject();
        if (persistable instanceof WorkItem)
        {
            WorkItem workItem = (WorkItem) persistable;
            WfAssignedActivity wfAssignedActivity = (WfAssignedActivity) workItem.getSource().getObject();
            reviewObjs =  (List) (wfAssignedActivity.getContext().getValue("reviewObjs"));
            WTPart pbo = (WTPart) (wfAssignedActivity.getContext().getValue("primaryBusinessObject"));
            boolean flag = doCollectOperation(nmcommandbean, pbo, reviewObjs);
            if (flag) //更新流程变量
            {
                wfAssignedActivity.getContext().setValue("reviewObjs", reviewObjs);
                PersistenceHelper.manager.save(wfAssignedActivity);
            }
        }
        formresult.setNextAction(FormResultAction.REFRESH_CURRENT_PAGE);
        super.doOperation(nmcommandbean, list);
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doOperation()");
        return formresult;
    }

    protected FormResult setRefreshInfo(FormResult formresult, NmCommandBean nmcommandbean, List list) throws WTException
    {
        DynamicRefreshInfo dynamicrefreshinfo = new DynamicRefreshInfo();
        dynamicrefreshinfo.setLocation(nmcommandbean.getActionOid());
        dynamicrefreshinfo.setOid(nmcommandbean.getActionOid());
        NmCommandBean _tmp = nmcommandbean;
        dynamicrefreshinfo.setAction("U");
        formresult.addDynamicRefreshInfo(dynamicrefreshinfo);
        return formresult;
    }

    /**
     *更新所选对象:如果所选对象不是最新版本，则获取最新版本，请更新至随签对象列表中
     */
    public static boolean doCollectOperation(NmCommandBean nmcommandbean, WTPart pbo, List reviewObjs) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doCollectOperation()");
        String action = nmcommandbean.getTextParameter("executeLocation");
        HashMap map = nmcommandbean.getParameterMap();
        boolean flag = false;
        if (VERBOSE)
        {
            Iterator keys = map.keySet().iterator();
            while (keys.hasNext())
            {
                Object key = keys.next();
                System.out.println("	" + key + "=" + nmcommandbean.getTextParameter(key.toString()));
            }
        }
        if (action.equals("collect_review_caddoc"))
        {
            flag = doCollectCADDocumentOperation(nmcommandbean, pbo, reviewObjs);
        }
        else if (action.equals("collect_review_doc"))
        {
            flag = doCollectDocumentOperation(nmcommandbean, pbo, reviewObjs);
        }
        else if (action.equals("collect_review_part"))
        {
            flag = doCollectPartOperation(nmcommandbean, pbo, reviewObjs);
        }

        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doCollectOperation()");
        return flag;
    }

    /**
     *根据所选对象，收集可以随签的CAD文档
     */
    private static boolean doCollectCADDocumentOperation(NmCommandBean nmcommandbean, WTPart pbo, List reviewObjs) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doCollectCADDocumentOperation()");
        ArrayList list = nmcommandbean.getSelected();
        if (VERBOSE)
        {
            System.out.println("	" + list.size() + " objects are selected!");
        }
        Hashtable objectCache = new Hashtable();
        for (int i = 0; i < list.size(); i++)
        {
            NmContext nmcontext = (NmContext) list.get(i);
            WTObject obj = (WTObject) nmcontext.getTargetOid().getWtRef().getObject();
            if (obj instanceof WTPart)
            {
                PartWorkflowUtil.getReviewCADDocuments((WTPart) obj, pbo, objectCache);
            }
        }
        boolean flag = false;
        Enumeration keys = objectCache.keys();
        while (keys.hasMoreElements())
        {
            Object obj = objectCache.get(keys.nextElement());
            if (!reviewObjs.contains(obj))
            {
                reviewObjs.add(obj);
                flag = true;
                if (VERBOSE)
                    System.out.println("	" + ((WTObject) obj).getDisplayIdentity() + " is add into reviewObjects!");
            }

        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doCollectCADDocumentOperation()--flag=" + flag);
        return flag;
    }

    /**
     *根据所选对象，收集可以随签的文档
     */
    private static boolean doCollectDocumentOperation(NmCommandBean nmcommandbean, WTPart pbo, List reviewObjs) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doCollectDocumentOperation()");
        ArrayList list = nmcommandbean.getSelected();
        if (VERBOSE)
        {
            System.out.println("	" + list.size() + " objects are selected!");
        }
        Hashtable objectCache = new Hashtable();
        for (int i = 0; i < list.size(); i++)
        {
            NmContext nmcontext = (NmContext) list.get(i);
            WTObject obj = (WTObject) nmcontext.getTargetOid().getWtRef().getObject();
            if (obj instanceof WTPart)
            {
            	PartWorkflowUtil.getReviewDocuments((WTPart) obj, pbo, objectCache);
            }
        }
        boolean flag = false;
        Enumeration keys = objectCache.keys();
        while (keys.hasMoreElements())
        {
            Object obj = objectCache.get(keys.nextElement());
            if (!reviewObjs.contains(obj))
            {
                reviewObjs.add(obj);
                flag = true;
                if (VERBOSE)
                    System.out.println("	" + ((WTObject) obj).getDisplayIdentity() + " is add into reviewObjects!");
            }

        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doCollectDocumentOperation()--flag=" + flag);
        return flag;
    }

    /**
     *根据所选对象，收集可以随签的零部件
     */
    private static boolean doCollectPartOperation(NmCommandBean nmcommandbean, WTPart pbo, List reviewObjs) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doCollectPartOperation()");
        ArrayList list = nmcommandbean.getSelected();
        if (VERBOSE)
        {
            System.out.println("	" + list.size() + " objects are selected!");
        }
        Hashtable objectCache = new Hashtable();
        for (int i = 0; i < list.size(); i++)
        {
            NmContext nmcontext = (NmContext) list.get(i);
            WTObject obj = (WTObject) nmcontext.getTargetOid().getWtRef().getObject();
            if (obj instanceof WTPart)
            {
                PartWorkflowUtil.getReviewParts((WTPart) obj, pbo, objectCache);
            }
        }
        boolean flag = false;
        Enumeration keys = objectCache.keys();
        while (keys.hasMoreElements())
        {
            Object obj = objectCache.get(keys.nextElement());
            if (!reviewObjs.contains(obj))
            {
                reviewObjs.add(obj);
                flag = true;
                if (VERBOSE)
                    System.out.println("	" + ((WTObject) obj).getDisplayIdentity() + " is add into reviewObjects!");
            }
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doCollectPartOperation()--flag=" + flag);
        return flag;
    }
}
